using Microsoft.AspNetCore.Mvc;
using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;

namespace SheLife.Api.Controllers
{
    /// <summary>
    /// 健康记录管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HealthRecordsController : ControllerBase
    {
        private readonly IHealthRecordService _healthRecordService;

        public HealthRecordsController(IHealthRecordService healthRecordService)
        {
            _healthRecordService = healthRecordService;
        }

        /// <summary>
        /// 获取健康记录详情
        /// </summary>
        /// <param name="id">健康记录ID</param>
        /// <returns>健康记录详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetHealthRecord(Guid id)
        {
            var healthRecord = await _healthRecordService.GetHealthRecordByIdAsync(id);
            if (healthRecord == null)
            {
                return NotFound();
            }

            return Ok(healthRecord);
        }

        /// <summary>
        /// 获取用户的健康记录列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="type">健康记录类型</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>健康记录列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetHealthRecords(
            [FromQuery] Guid userId,
            [FromQuery] string? type = null,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            var healthRecords = await _healthRecordService.GetHealthRecordsByUserIdAsync(userId, type, startDate, endDate);
            return Ok(healthRecords);
        }

        /// <summary>
        /// 创建健康记录
        /// </summary>
        /// <param name="model">健康记录创建模型</param>
        /// <returns>创建的健康记录</returns>
        [HttpPost]
        public async Task<IActionResult> CreateHealthRecord([FromBody] CreateHealthRecordModel model)
        {
            try
            {
                var healthRecord = await _healthRecordService.CreateHealthRecordAsync(
                    model.UserId,
                    model.Type,
                    model.Title,
                    model.Description,
                    model.RecordDate,
                    model.Data);

                return CreatedAtAction(nameof(GetHealthRecord), new { id = healthRecord.Id }, healthRecord);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 更新健康记录
        /// </summary>
        /// <param name="id">健康记录ID</param>
        /// <param name="model">健康记录更新模型</param>
        /// <returns>更新后的健康记录</returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateHealthRecord(Guid id, [FromBody] UpdateHealthRecordModel model)
        {
            var healthRecord = await _healthRecordService.UpdateHealthRecordAsync(
                id,
                model.Type,
                model.Title,
                model.Description,
                model.RecordDate,
                model.Data);

            if (healthRecord == null)
            {
                return NotFound();
            }

            return Ok(healthRecord);
        }

        /// <summary>
        /// 删除健康记录
        /// </summary>
        /// <param name="id">健康记录ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteHealthRecord(Guid id)
        {
            var result = await _healthRecordService.DeleteHealthRecordAsync(id);
            if (!result)
            {
                return NotFound();
            }

            return Ok(new { message = "健康记录删除成功" });
        }

        /// <summary>
        /// 获取生理周期记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>生理周期记录列表</returns>
        [HttpGet("menstrual-cycle")]
        public async Task<IActionResult> GetMenstrualCycleRecords(
            [FromQuery] Guid userId,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            var records = await _healthRecordService.GetHealthRecordsByUserIdAsync(userId, "MenstrualCycle", startDate, endDate);
            return Ok(records);
        }

        /// <summary>
        /// 创建生理周期记录
        /// </summary>
        /// <param name="model">生理周期记录创建模型</param>
        /// <returns>创建的生理周期记录</returns>
        [HttpPost("menstrual-cycle")]
        public async Task<IActionResult> CreateMenstrualCycleRecord([FromBody] CreateMenstrualCycleModel model)
        {
            try
            {
                // 将生理周期数据序列化为JSON
                var data = new
                {
                    model.StartDate,
                    model.EndDate,
                    model.FlowIntensity,
                    model.Symptoms,
                    model.Notes
                };

                var healthRecord = await _healthRecordService.CreateHealthRecordAsync(
                    model.UserId,
                    "MenstrualCycle",
                    "生理周期记录",
                    $"记录时间：{model.StartDate:yyyy-MM-dd} 至 {model.EndDate:yyyy-MM-dd}",
                    model.StartDate,
                    System.Text.Json.JsonSerializer.Serialize(data));

                return CreatedAtAction(nameof(GetHealthRecord), new { id = healthRecord.Id }, healthRecord);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 健康记录创建模型
    /// </summary>
    public class CreateHealthRecordModel
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 健康记录类型
        /// </summary>
        public string Type { get; set; } = string.Empty;

        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; } = string.Empty;

        /// <summary>
        /// 描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 记录日期
        /// </summary>
        public DateTime RecordDate { get; set; }

        /// <summary>
        /// 数据（JSON格式）
        /// </summary>
        public string? Data { get; set; }
    }

    /// <summary>
    /// 健康记录更新模型
    /// </summary>
    public class UpdateHealthRecordModel
    {
        /// <summary>
        /// 健康记录类型
        /// </summary>
        public string Type { get; set; } = string.Empty;

        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; } = string.Empty;

        /// <summary>
        /// 描述
        /// </summary>
        public string? Description { get; set; }

        /// <summary>
        /// 记录日期
        /// </summary>
        public DateTime RecordDate { get; set; }

        /// <summary>
        /// 数据（JSON格式）
        /// </summary>
        public string? Data { get; set; }
    }

    /// <summary>
    /// 生理周期记录创建模型
    /// </summary>
    public class CreateMenstrualCycleModel
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime EndDate { get; set; }

        /// <summary>
        /// 经血流量强度（1-5）
        /// </summary>
        public int FlowIntensity { get; set; }

        /// <summary>
        /// 症状列表
        /// </summary>
        public List<string>? Symptoms { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string? Notes { get; set; }
    }
}